<template>
    <div class="app-container">
        <el-form class="formBox formBox1" :model="form" :rules="rules" ref="form" size="small" :inline="true"
            label-width="90px">
            <el-row>
                <el-form-item label="顾客ID" prop="patientId">
                    <el-input v-model="queryParams.patientId" placeholder="请输入顾客编号" clearable style="width: 160px"
                        :disabled="true" />
                </el-form-item>
                <el-form-item label="姓名" prop="patientName" label-width="40px">
                    <el-input v-model="queryParams.patientName" placeholder="请输入顾客姓名" clearable style="width: 160px"
                        :disabled="true" />
                </el-form-item>
                <el-form-item label="顾客编号" prop="visitNum">
                    <el-input v-model="queryParams.visitNum" placeholder="请输入顾客编号" clearable style="width: 190px"
                        :disabled="true" />
                </el-form-item>
              <el-form-item label="就诊门诊" prop="patientName">
                <el-input v-model="queryParams.deptName" placeholder="请输入就诊科室" :disabled="true" clearable
                          style="width: 160px" />
              </el-form-item>
<!--                <el-form-item prop="deptId">-->
<!--                    <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="form.hospitalId"-->
<!--                        ref="department" deptWidth="160px" :deptIds="form.deptId" :isdisabled="true" v-if="open">-->
<!--                    </department>-->
<!--                </el-form-item>-->
            </el-row>


            <el-form-item label="预约信息" prop="appointmentDate" label-width="90px">
                <el-date-picker v-model="form.appointmentDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions0" style="width:160px" @change="changedate" :clearable="false">
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="week">
                <el-input v-model="form.week" placeholder="周几" :readonly="true" style="width:80px" />
            </el-form-item>
            <el-form-item prop="timeSlot">
                <el-select v-model="form.timeSlot" placeholder="时间" style="width:80px">
                    <el-option v-for="dict in sysUseTypeArr" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item prop="planId">
                <el-select v-model="form.planId" filterable placeholder="请选择治疗项目" clearable style="width: 140px"
                    @change="getName(1)">
                    <el-option v-for="item in singlePlanList" :key="item.planId" :label="item.medicalEquipment"
                        :value="item.planId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="doctorUsername">
                <el-select v-model="form.doctorUsername" filterable placeholder="请选择治疗医生" clearable style="width: 150px"
                    @change="getName(2)">
                    <el-option v-for="item in treatmentDoctorUsersList" :key="item.userId" :label="item.nickName"
                        :value="item.userName"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="remark">
                <el-input v-model="form.remark" placeholder="备注" style="width: 150px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-plus" size="small" plain @click="getappointmentScheduling"
                    :disabled="form.treatmentAppointmentId ? true : false">添加下次预约</el-button>
                <!-- <el-button type="danger" icon="el-icon-edit" :disabled="form.treatmentAppointmentId ? false : true"
                    size="small" plain @click="submitForm">修改下次预约</el-button> -->

            </el-form-item>
        </el-form>
        <div class="formBox">
            <div style="color:red;line-height:30px;">* 已预约的信息，在预约时间排班之后，可以进行重新选择可预约的时间段！（爽约、已签到均无法修改）</div>
            <el-table border v-loading="loading" :data="tablesList">

                <el-table-column sortable label="日期" align="center" prop="appointmentDate" :show-overflow-tooltip="true"
                    width="100" />
                <el-table-column sortable label="星期" align="center" prop="week" :show-overflow-tooltip="true" width="80">

                </el-table-column>


                <el-table-column sortable label="上、下午" width="120" align="center" prop="timeSlot"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <span v-if="scope.row.timeSlot == 0" style="color:red">上午</span>
                        <span v-else style="color:blue">下午</span>
                    </template>
                </el-table-column>
                <el-table-column sortable label="治疗项目" width="120" align="center" prop="medicalEquipment"
                    :show-overflow-tooltip="true">

                </el-table-column>
                <el-table-column label="是否排班" align="center" sortable prop="state" :show-overflow-tooltip="true"
                    width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.schedulingId" style="color:rgb(89, 0, 255)">已排班</span>

                        <span v-else style="color:rgb(138, 136, 136)">未排班</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" sortable prop="state" :show-overflow-tooltip="true" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.state == 5" style="color:rgb(47, 0, 255)">已确认</span>
                        <span v-else-if="scope.row.state == 1" style="color:rgb(0, 255, 34)">已签到</span>
                        <span v-else-if="scope.row.state == 2" style="color:rgb(105, 108, 109)">爽约</span>
                        <span v-else style="color:red">已预约</span>
                    </template>
                </el-table-column>
                <el-table-column sortable label="治疗医生" width="120" align="center" prop="doctorNickname"
                    :show-overflow-tooltip="true">

                </el-table-column>
                <el-table-column label="医院" align="center" prop="hospitalName" :show-overflow-tooltip="true" width="150">
                    <template slot-scope="scope">
                        <departTag :options="deptNameLists" :value="scope.row.hospitalId" />
                    </template>
                </el-table-column>
                <el-table-column label="科室" align="center" prop="deptName" :show-overflow-tooltip="true" width="150">
                    <template slot-scope="scope">
                        <departTag :options="deptNameLists" :value="scope.row.deptId" />
                    </template>
                </el-table-column>
                <el-table-column sortable label="创建时间" align="center" prop="createTime" width="160">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column sortable label="备注" align="center" prop="remark" :show-overflow-tooltip="true">

                </el-table-column>

                <!-- <el-table-column  label="备注" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
                <el-table-column label="操作" align="center" fixed="right" width="140" class-name="small-padding fixed-width">
                    <template slot-scope="scope" v-if="!loading">
                        <el-button size="mini" type="text" icon="el-icon-edit"
                            v-if="scope.row.state == 0 && scope.row.schedulingId"
                            @click="handleUpdate(scope.row)">修改</el-button>
                        <el-button size="mini" type="text" icon="el-icon-edit" v-else :disabled="true">修改</el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.state == 0"
                            @click="handleDelete(scope.row, 1)">删除</el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" v-else :disabled="true">删除</el-button>
                        <el-button size="mini" type="text" icon="el-icon-mouse" v-if="(scope.row.state == 0||scope.row.state == 5)&&scope.row.schedulingId"
                            @click="handleSure(scope.row, 4)">确认签到</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>

        <!-- 弹出预约提示 -->
        <el-dialog title="预约信息" :visible.sync="appointTipDialogVisible" v-dialogDrag width="70%" append-to-body
            :close-on-click-modal="false">
            <appointTip v-if="appointTipDialogVisible" :appointItem="appointItem" type="1"
                @closeappointTipDialogVisible="closeappointTipDialogVisible" @comfirm="sureComfire">
            </appointTip>
        </el-dialog>

        <!-- 弹出预约提示 -->
        <el-dialog title="修改预约信息" :visible.sync="appointTimeDialogVisible" v-dialogDrag width="500px" append-to-body
            :close-on-click-modal="false">
            <appointTime :formBacie="formBacie" @refresh="getList"></appointTime>
        </el-dialog>
    </div>
</template>

<script>
import { getAppointment, listAllAppointment, updateSysTreatmentAppointmentStateById, addAppointment, updateAppointment, delAppointment, appointmentScheduling } from "@/api/appointManage/appointReserve";
import { getListUser } from "@/api/system/user";
import { deptNameList } from "@/api/system/dept";
import { getVisitDept } from "@/api/patientRegistration/registrationList";
import {
    listPlan,listPlanDept
} from "@/api/system/plan";
import departTag from "@/views/components/department/departTag.vue";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import department from "@/views/components/department/index.vue";
import appointTip from "@/views/components/customerDetail/appointTip.vue";
import appointTime from "@/views/components/customerDetail/appointTime.vue";
export default {
    name: "appointReservate",
    dicts: ["sys_textmanage_type", 'sys_manage_diseases'],
    components: { department, departTag, appointTip, appointTime },
    props: ["basicInfo"],
    data() {
        return {
            pickerOptions0: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '一周以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '2周以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 14);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '30天以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '60天以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 60);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '90天以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '6个月以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 30 * 6);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '1年以后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 365);
                        picker.$emit('pick', date);
                    }
                }]
            },
            appointTimeDialogVisible: false,
            tablesList: [],
            sysUseTypeArr: [
                { label: '上午', value: 0 },
                { label: '下午', value: 1 }

            ],
            treatmentDoctorUsersList: [],//治疗医生
            // 总条数
            total: 0,
            form: {
                treatmentAppointmentId: undefined,
                schedulingId: undefined,
                appointmentDate: '',
                week: '',
                timeSlot: 0,
                planId: '',
                medicalEquipment: '',

                doctorUsername: '',
                doctorNickname: '',
                deptId: '',
                hospitalId: '',
                remark: '',
                way: 0, //0 pc 端 1 小程序
                patientId: undefined,
            },
            formBacie: {},
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                hospitalId: undefined,
                deptId: undefined,
                patientId: undefined,
                patientName: undefined,
                visitNum: undefined
            },
            // 表单校验
            rules: {
                appointmentDate: [
                    {
                        required: true,
                        message: "日期必选!",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "科室必选!",
                        trigger: "blur",
                    },
                ],
                planId: [
                    {
                        required: true,
                        message: "治疗项目必选!",
                        trigger: "blur",
                    },
                ],


            },
            loading: false,
            deptNameLists: [],
            singlePlanList: [],
            open: false,
            appointItem: {},
            appointTipDialogVisible: false,
        }
    },

    mounted() {
        console.log(this.basicInfo)
        this.queryParams.patientId = this.basicInfo.patientId
        this.queryParams.patientName = this.basicInfo.patientName
        this.queryParams.visitNum = this.basicInfo.visitNum
        this.queryParams.deptName = this.basicInfo.deptName
        this.form.deptId=this.basicInfo.deptId
        this.getCVisitDept()

        this.getSinglePlanList()
        this.getTreatmentDoctorUsersList()
    },
    methods: {
        closeappointTipDialogVisible() {
            this.appointTipDialogVisible = false
        },

        getCVisitDept() {
            let params = {
                visitNum: this.queryParams.visitNum
            }
            getVisitDept(params).then((response) => {
                let data = response.data
                this.queryParams.deptId = data.deptId
                this.queryParams.hospitalId = data.hospitalId
                this.reset();
                this.getdeptNameList()
            });
        },
        // 回显医院及门诊
        getdeptNameList() {
            deptNameList().then((response) => {
                this.deptNameLists = response.data;
                this.handleQuery()
            });
        },
        selectable(row, index) {
            var strtime = row.appointmentDate.replace("/-/g", "/");//时间转换
            var date1 = new Date(strtime);//现在时间
            var date2 = new Date();
            var d2 = date2.getFullYear() + "/" + (date2.getMonth() + 1) + "/" + date2.getDate()
            var date3 = new Date(d2);
            //判断时间是否过期
            return date1 < date3 ? false : true;
        },
        getName(type) {
            let textValue = "";
            if (type == 2) {
                this.treatmentDoctorUsersList.forEach((item) => {
                    if (item.userName == this.form.doctorUsername) {
                        textValue = item.nickName;
                    }
                });
                this.form.doctorNickname = textValue;
            } else if (type == 1) {
                this.singlePlanList.forEach((item) => {
                    if (item.planId == this.form.planId) {
                        textValue = item.medicalEquipment;
                    }
                });
                this.form.medicalEquipment = textValue;
            }

        },
        changedepatData(data) {
            // if (data && data.length > 0) {
            //     this.form.deptId = data[0].deptId
            //     this.form.hospitalId = data[0].parentId
            // } else {
            //     this.form.deptId = undefined
            //     this.form.hospitalId = undefined
            // }
            this.getSinglePlanList()
            this.getTreatmentDoctorUsersList()
        },
        changedate() {
            let date = this.form.appointmentDate
            var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
            var week = weekArray[new Date(date).getDay()];//注意此处必须是先new一个Date

            this.form.week = "周" + week;
        },
        //查询治疗医生列表
        getTreatmentDoctorUsersList() {
            getListUser({ funcRole: '3', deptId: this.form.deptId }).then((response) => {
                if (response.code == 200) {
                    this.treatmentDoctorUsersList = response.data
                }
            });

        },
        /** 治疗项目 */
        getSinglePlanList() {
            listPlanDept({
                pageNum: 1,
                pageSize: 9999,
                status: 0,
                deptId: this.form.deptId,
                planCategoryId: "2"
            }).then(
                (response) => {
                    this.singlePlanList = response.rows;
                }
            );
        },

        /** 查询设备列表 */
        getList() { // this.queryParams
            this.loading = true;
            let that = this
            let params = {
                patientId: that.queryParams.patientId,
            }
            listAllAppointment(params).then((response) => {
                this.tablesList = response.data;
                this.loading = false;
                this.appointTimeDialogVisible = false
            });
        },


        // 表单重置
        reset() {
            this.resetForm("form");
            this.form = {
                treatmentAppointmentId: undefined,
                schedulingId: undefined,
                appointmentDate: '',
                week: '',
                timeSlot: 0,
                planId: '',
                medicalEquipment: '',

                doctorUsername: '',
                doctorNickname: '',
                deptId: this.queryParams.deptId,
                hospitalId: this.queryParams.hospitalId,
                remark: '',
                way: 0, //0 pc 端 1 小程序
                patientId: this.queryParams.patientId,
            },
                console.log(this.form)
            this.open = false
            this.getSinglePlanList()
            this.getTreatmentDoctorUsersList()
            setTimeout(() => {
                this.open = true
            }, 100);
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },


        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            // this.open = false
            const treatmentAppointmentId = row.treatmentAppointmentId;
            getAppointment(treatmentAppointmentId).then((response) => {
                let data = response.data;
                this.formBacie = data
                this.appointTimeDialogVisible = true
                this.getSinglePlanList()
                this.getTreatmentDoctorUsersList()
                // this.open = true
            });
        },
        sureupdateSysTreatmentAppointmentStateById(id) {
            let params = {
                treatmentAppointmentId: id,
                state: 1
            }
            updateSysTreatmentAppointmentStateById(params).then((response) => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("预约已成功签到~");
                    this.getList();
                }
            });
        },
        //handleSure
        handleSure(row) {
            const title = row.appointmentDate + row.week
            const treatmentAppointmentId = row.treatmentAppointmentId;
            let that = this
            this.$modal.confirm(
                '是否确认"' +
                title +
                '"已履约，并签到？'
            )
                .then(function () {
                    console.log('点击确认')
                    that.sureupdateSysTreatmentAppointmentStateById(treatmentAppointmentId);
                })

                .catch(() => { });

        },
        //查询预约信息 appointmentScheduling
        getappointmentScheduling() {
            this.$refs["form"].validate((valid) => {
                let that = this
                if (valid) {
                    appointmentScheduling(this.form).then((response) => {
                        if (response.code == 200) {
                            let data = response.data
                            //查询信息，弹出提示
                            console.log(data)
                            that.appointItem = data
                            that.appointTipDialogVisible = true
                        }
                    });
                }
            });
        },
        sureComfire(data) {//确认预约
            let obj = data[0]
            this.form.open = obj.open ? 1 : 0
            this.submitForm()

        },
        /** 提交按钮 */
        submitForm: function () {
            console.log(this.$refs["form"])
            this.$refs["form"].validate((valid) => {
                let that = this
                if (valid) {
                    if (this.form.treatmentAppointmentId != undefined) {

                        updateAppointment(this.form).then((response) => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess("修改预约成功");
                                this.reset()
                                this.getList();
                                this.appointTipDialogVisible = false
                            }
                        });
                    } else {

                        addAppointment(this.form).then((response) => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess("预约成功");
                                this.reset()
                                this.getList();
                                this.appointTipDialogVisible = false
                            }

                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row, type) {
            if (type == 1) { //单个删除
                const title = row.appointmentDate + row.week
                const treatmentAppointmentId = row.treatmentAppointmentId;
                this.$modal.confirm(
                    '是否确认"' +
                    title +
                    '"的数据项？'
                )
                    .then(function () {
                        return delAppointment(treatmentAppointmentId);
                    })
                    .then(() => {
                        this.getList();
                        // this.$modal.msgSuccess("删除预约成功");
                    })
                    .catch(() => { });
            }
        },
    },
    created() {

    }
}
</script>

<style scoped rel="stylesheet/scss"  lang="scss"></style>
